package com.cims.dao.staff;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.cims.common.exception.DaoException;
import com.cims.common.vo.Staff;
import com.cims.common.vo.User;
import com.cims.dao.hibernate.HibernateUtil;

public class StaffDAOImpl  implements StaffDAO {

	@Override
	public int authenticate(String username, String password){
		Staff s = HibernateUtil.findOne(Staff.class, "from Staff where user.username='" + username + "' and user.password='" + password + "'");
		if(s != null && s.getStaffId() >=0){
			return s.getStaffId();
		}else{
			return -1;
		}
	}
	
	@Override
	public List<Staff> getListStaff() throws DaoException {
		return HibernateUtil.selectAll(Staff.class);
	}
	
	@Override
	public Staff findByStaffId(int staffId) throws DaoException {
		// TODO Auto-generated method stub
		return HibernateUtil.findByID(Staff.class, staffId) ;
	}

	@Override
	public boolean update(Staff sta) throws DaoException {
		// TODO Auto-generated method stub
		return HibernateUtil.updateVo(sta);
	}

	@Override
	public boolean insert(Staff sta) throws DaoException {
		
		return HibernateUtil.insertVo(sta);
	}

	@Override
	/*public boolean delete(Staff sta) throws DaoException {
		// TODO Auto-generated method stub
		return HibernateUtil.deleteVo(sta);
	}*/
	public void delete(int staffId) throws DaoException{
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = null;
		Transaction trans = null;
		try {
			session = factory.openSession();
			trans = session.beginTransaction();

			Staff s = (Staff)session.get(Staff.class, staffId);
			session.delete(s);
			trans.commit();
			trans = null;
		} catch (Exception ex) {
			ex.printStackTrace();
			if (trans != null) {
				trans.rollback();
				trans = null;
			}
		} finally {
			if (trans != null) {
				trans.rollback();
				trans = null;
			}
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}


}
